package com.guodi.model.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.common.utils.SortListUtil;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.model.constant.ModelConst;
import com.guodi.model.entity.*;
import com.guodi.model.service.*;
import com.guodi.model.utils.RecursionUtils;
import com.guodi.model.utils.VerificationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @描述：模型目录表控制类
 * @作者: 代鹏刚
 * @日期: 2020-06-17
 */
@RestController
@RequestMapping("/MdlModelDir")
@Api(value = "API - MdlModelDirController", tags = "模型目录表")
public class MdlModelDirController extends BaseController {

    @Resource
    public IMdlModelDirService mdlModelDirService;
    @Resource
    private IMdlModelService mdlModelService;

    @Resource
    public IMdlModelTypeService mdlModelTypeService;
    @Resource
    public IMdlModelResultService mdlModelResultService;

    @Resource
    private IIdModelLayerService iIdModelLayerService;

    //指标图片存储路径
    private static String MODEL_PIC_PATH = "Model/images/";

    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * @描述: 获取模型目录树列表
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/4/3 11:48
     **/
    @PostMapping("/listDirTreeByEntity")
    @ApiOperation(value = " 获取模型目录树列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级目录ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "模型体系code", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "dirType", value = "目录/模型类型(1表示目录, 2表示模型)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "returnType", value = "返回格式(1:列表 2:树)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "searchType", value = "查询类型（1：关联图层查询）", dataType = "string", paramType = "query")
    })
    public AjaxResult listDirTreeByEntity(String parentId, Integer dirType, String returnType, String searchType, String code) {
        // 新增根据模型体系查询
        if(null == parentId && null != code){
            List<MdlModelType> mdlModelTypes = mdlModelTypeService.listByMap(VerificationUtils.verifyMapByCode(null, code));
            if(mdlModelTypes.size() > 0){
               parentId = mdlModelTypes.get(0).getId();
            }else {
                return new AjaxResult(StatusCode.ERROR_CODE_40005,"模型体系code不存在");
            }
        }else if(null == parentId && null == code){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"模型体系code不能为空");
        }
        if(returnType.equals("1")){
            List<MdlModelDir> dataList = mdlModelDirService.listDirTreeByEntity(parentId,dirType);
            // 排序
            SortListUtil.sort(dataList,"getSort","asc");
            // 如果是postgreSQL，他是没有顺序的，所以需要额外进行排序
            boolean isTrue = dataList.stream().filter(m -> m.getTreeLevel() == 0).findAny().isPresent();
            if(isTrue){
                if ("1".equals(searchType)) {
                    // 过滤模型，只显示目录
                    dataList = dataList.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());
                    List<IdtModelLayer> relLayerList = iIdModelLayerService.getListBySystemId(parentId);
                    // 排序
                    SortListUtil.sort(relLayerList,"getSort","asc");
                    for (IdtModelLayer idtModelLayer : relLayerList) {
                        MdlModelDir mdlModelDir = new MdlModelDir();
                        mdlModelDir.setId(idtModelLayer.getId());
                        mdlModelDir.setParentId(idtModelLayer.getParentId());
                        mdlModelDir.setName(idtModelLayer.getLayerName());
                        mdlModelDir.setType(3);
                        mdlModelDir.setAlias(idtModelLayer.getAlias());
                        // 新增图层目录
                        if (idtModelLayer.getDataType() == 0) {
                            mdlModelDir.setType(4);
                        }
                        mdlModelDir.setSort(idtModelLayer.getSort());
                        mdlModelDir.setIdtModelLayer(idtModelLayer);
                        dataList.add(mdlModelDir);
                    }
                }
                List<MdlModelDir> resultList = new ArrayList<>();
                sortList(dataList,parentId,resultList, null);
                return new AjaxResult(resultList);
            }else {
                if ("1".equals(searchType)) {
                    // 过滤模型，只显示目录
                    dataList = dataList.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());
                    List<IdtModelLayer> relLayerList = iIdModelLayerService.getListBySystemId(parentId);
                    for (IdtModelLayer idtModelLayer : relLayerList) {
                        MdlModelDir mdlModelDir = new MdlModelDir();
                        mdlModelDir.setId(idtModelLayer.getId());
                        mdlModelDir.setParentId(idtModelLayer.getParentId());
                        mdlModelDir.setName(idtModelLayer.getLayerName());
                        mdlModelDir.setType(3);
                        mdlModelDir.setAlias(idtModelLayer.getAlias());
                        // 新增图层目录
                        if (idtModelLayer.getDataType() == 0) {
                            mdlModelDir.setType(4);
                        }
                        mdlModelDir.setSort(idtModelLayer.getSort());
                        mdlModelDir.setIdtModelLayer(idtModelLayer);
                        dataList.add(mdlModelDir);
                    }
                    // 如果是oracle，那么查询图层后也要进行排序
                    List<MdlModelDir> resultList = new ArrayList<>();
                    sortList(dataList,parentId,resultList, null);
                    dataList = resultList;
                }
                return new AjaxResult(dataList);
            }
        }else {
            return new AjaxResult(RecursionUtils.buildModelDirTree(mdlModelDirService.listDirTreeByEntity(parentId,dirType),parentId));
        }
    }
    private static void sortList(List<MdlModelDir> list, String id, List<MdlModelDir> resultList, MdlModelDir mdlModelDir) {
        for (MdlModelDir node :list) {
            if (node.getParentId().equals(id)) {
                if (mdlModelDir != null && mdlModelDir.getTreeLevel() != null) {
                    node.setTreeLevel(mdlModelDir.getTreeLevel() + 1);
                } else {
                    node.setTreeLevel(node.getTreeLevel() + 1);
                }
                resultList.add(node);
                sortList(list,node.getId(),resultList,node);
            }
        }
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-06-17
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult findById(String id) {
        if(StringUtils.isBlank(id)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MdlModelDir mdlModelDir = mdlModelDirService.getById(id);
        return new AjaxResult(mdlModelDir);
    }

    /**
     * @描述: 新增目录
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-06-17
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级目录ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "目录名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "icon", value = "图标", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态(1.启用, 0:禁用)", required = true, dataType = "int", paramType = "query")
    })
    public AjaxResult save(@ApiIgnore MdlModelDir mdlModelDir){
        if(!prepareData(mdlModelDir, true)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"该目录名称已经存在，请更换！");
        }
        mdlModelDir.setId(UuidUtil.get32UUID());
        mdlModelDir.setType(1);
        String deptId = this.getUser().getDeptId();
        if(StringUtils.isNotBlank(deptId)){
            mdlModelDir.setOrgId(deptId);
        }
        if ("null".equals(mdlModelDir.getIcon())) {
            mdlModelDir.setIcon(null);
        }
        mdlModelDirService.save(mdlModelDir);
        return new AjaxResult(mdlModelDir);
    }

    /**
     * @描述: 修改目录
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-06-17
     **/
    @PostMapping("/updateDir")
    @ApiOperation(value = "修改目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "目录名称",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序",  dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "icon", value = "图标", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态(1.启用, 0:禁用)", dataType = "int", paramType = "query")
    })
    public AjaxResult updateDir(MdlModelDir mdlModelDir) {
        if(!prepareData(mdlModelDir, false)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"该目录名称已经存在，请更换！");
        }
        if ("null".equals(mdlModelDir.getIcon())) {
            mdlModelDir.setIcon(null);
        }
        mdlModelDirService.updateById(mdlModelDir);
        MdlModelDir modelDir = mdlModelDirService.getById(mdlModelDir.getId());
        modelDir.setParentName(mdlModelDir.getParentName());
        return new AjaxResult(modelDir);
    }

    /**
    * @描述: 修改模型
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/6/18 11:24
    **/
    @PostMapping("/updateModel")
    @ApiOperation(value = "修改模型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模型名称",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alias", value = "模型别名",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "dataType", value = "数据类型（MONITOR：监测值，TARGET：目标值，REPORT：上报值）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序",  dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "icon", value = "图标",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态(1.启用, 0:禁用)", dataType = "int", paramType = "query")
    })
    public AjaxResult updateModel(@ApiIgnore MdlModelDir mdlModelDir, String deleteFileStr, @RequestParam(required = false,value = "file") MultipartFile file) throws Exception{
        MdlModelDir mdlModelDirData = mdlModelDirService.getById(mdlModelDir.getId());
        if(null != file){
            if(StringUtils.isNotBlank(mdlModelDirData.getImageUrl())){
//                String group = mdlModelDirData.getImageUrl().substring(0, mdlModelDirData.getImageUrl().indexOf("/"));
                MinioUtil.delete(bucketName, mdlModelDirData.getImageUrl());
            }
            //上传文件
//            String fileFormat = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String filePath = MinioUtil.uploadFile(file.getInputStream(), MODEL_PIC_PATH + mdlModelDir.getId() + "/" + file.getOriginalFilename());
            mdlModelDir.setImageUrl(filePath);
        }else {
            if ("1".equals(deleteFileStr)) {
                if(StringUtils.isNotBlank(mdlModelDirData.getImageUrl())){
//                    String group = mdlModelDirData.getImageUrl().substring(0, mdlModelDirData.getImageUrl().indexOf("/"));
                    MinioUtil.delete(bucketName, mdlModelDirData.getImageUrl());
                    mdlModelDir.setImageUrl("");
                }
            } else {
                mdlModelDir.setImageUrl(mdlModelDirData.getImageUrl());
            }
        }
        if(!prepareData(mdlModelDir, false)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"该模型名称已经存在，请更换！");
        }
        mdlModelDirService.updateById(mdlModelDir);
        return new AjaxResult(mdlModelDirService.getById(mdlModelDir.getId()));
    }

    /**
     * @描述: 根据主键批量删除
     * @入参: ids
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-06-17
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "多个使用逗号隔开", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult delete(String ids){
        String[] id = ids.split(",");
        mdlModelDirService.deleteByIds(id);
        return new AjaxResult();
    }

    /**
     * @描述: 获取当前目录未关联的模型
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-06-17
     **/
    @PostMapping("/getUnClassifyList")
    @ApiOperation(value = " 获取当前目录未关联的模型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级目录ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模型名称",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面下标", required = true, dataType = "int", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int", paramType = "query", example = "10")
    })
    public AjaxResult getUnClassifyList(@ApiIgnore Page page, String parentId, String name) {

        QueryWrapper<MdlModel> wrapper = new QueryWrapper();
        wrapper.notInSql("id", "select model_id from MDL_MODEL_DIR t where parent_id = '" + parentId + "'and t.model_id is not null");

        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", name);
        }
        IPage<IdtIndicators> iPage = mdlModelService.page(page, wrapper);

        return new AjaxResult(iPage);
    }

    /**
     * @描述: 保存模型列表目录关联的模型
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/4/3 10:56
     **/
    @PostMapping("/saveLinkModel")
    @ApiOperation(value = " 保存模型列表目录关联的模型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "当前选中目录ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "checkedIds", value = "关联模型ID(多个使用逗号隔开)", dataType = "string", paramType = "query")
    })
    public AjaxResult saveLinkModel(String parentId, String checkedIds) {
        List<MdlModelDir> resultList = new ArrayList<>();
        if (StringUtils.isNotBlank(checkedIds)) {
            String[] modelIds = checkedIds.split(",");
            for (int i = 0; i < modelIds.length; i++) {
                //获取默认的名称为模型名称
                String modelId = modelIds[i];
                MdlModel model = mdlModelService.getById(modelId);
                //根据parentId判断该目录下是否已关联模型
                List<MdlModelDir> list = (List<MdlModelDir>)mdlModelDirService.listByMap(VerificationUtils.verifyMapByModel(parentId,2));
                Integer sort = list.size() + 1;
                MdlModelDir mdlModelDir = new MdlModelDir();
                mdlModelDir.setId(UuidUtil.get32UUID());
                if (null != this.getUser()) {
                    mdlModelDir.setCreator(this.getUser().getUserId().toString());
                }
                mdlModelDir.setCreateTime(new Date());
                mdlModelDir.setType(2);
                mdlModelDir.setName(model.getName());
                // 默认别名
                mdlModelDir.setAlias(model.getName());
                mdlModelDir.setParentId(parentId);
                mdlModelDir.setDataType(model.getType());
                mdlModelDir.setUseCount(model.getUseCount());
                mdlModelDir.setSort(sort);
                mdlModelDir.setStatus(1);
                mdlModelDir.setModelId(modelId);
                resultList.add(mdlModelDir);
            }
           mdlModelDirService.saveBatch(resultList);
        }
        return new AjaxResult(resultList);
    }


    private boolean prepareData(MdlModelDir mdlModelDir, boolean isSave) {
        String parentId = mdlModelDir.getParentId();
        // 如果是修改，但是没有带上parentId，就查一下
        if(!isSave && !StringUtils.isNotBlank(mdlModelDir.getParentId())){
            MdlModelDir modelDir = this.mdlModelDirService.getById(mdlModelDir.getId());
            parentId = modelDir == null? null: modelDir.getParentId();
        }
        Map map = VerificationUtils.verifyMapByName(parentId, mdlModelDir.getName());
        List<MdlModelDir> list = (List<MdlModelDir>)mdlModelDirService.listByMap(map);
        if(isSave){
            if(list.size() > 0){
                return false;
            }
            mdlModelDir.setCreator(this.getUser().getUserId().toString());
            mdlModelDir.setCreateTime(new Date());
            //防止误修改
            mdlModelDir.setModifier(null);
            mdlModelDir.setModifyTime(null);
            return true;
        }else{
            if(list.size() > 0 && !list.get(0).getId().equals(mdlModelDir.getId())){
                return false;
            }
            mdlModelDir.setModifier(this.getUser().getUserId().toString());
            mdlModelDir.setModifyTime(new Date());
            //防止误修改
            mdlModelDir.setCreator(null);
            mdlModelDir.setCreateTime(null);
            return true;
        }
    }

    /**
    * @描述:根据编号查询模型目录树
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/6/22 11:57
    **/
    @PostMapping("/listDirTreeByCode")
    @ApiOperation(value = " 获取模型目录树列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isQueryResult", value = "是否查询模型结果",  dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "areaCode", value = "城市编码（不传查询整个模型结果数据，传了只返回传入城市及其下级城市的模型结果数据）", dataType = "string", paramType = "query")
    })
    public AjaxResult listDirTreeByCode(String code, boolean isQueryResult, String year, String areaCode, String keyword) {
        if(StringUtils.isBlank(code)){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"模型类型编码不能为空");
        }
        if(isQueryResult && StringUtils.isBlank(year)){
           return new AjaxResult(StatusCode.ERROR_CODE_40005,"查询模型结果年份必传");
        }
        Map<String, String> keys = new HashMap();
        LambdaQueryWrapper<MdlModelType> lambda = new QueryWrapper().lambda();
        lambda.eq(MdlModelType::getCode,code);
        MdlModelType one = mdlModelTypeService.getOne(lambda);
        List<ApiMdlModelDir> mdlModelDirs = mdlModelDirService.listTreeByEntity(one.getId(), null);
        // 排序
        SortListUtil.sort(mdlModelDirs,"getSort","asc");

        if(mdlModelDirs!=null && !mdlModelDirs.isEmpty()){
            Iterator<ApiMdlModelDir> iterator = mdlModelDirs.iterator();
            while (iterator.hasNext()) {
                ApiMdlModelDir item = iterator.next();
                String modelId = item.getModelId();
                item.setTypeCode(item.getId());
                if(StringUtils.isNotBlank(modelId)){
                    //按关键字（名称）过滤最后一级
                    if(StringUtils.isNotBlank(keyword)&&!item.getName().contains(keyword)){
                        iterator.remove();
                        continue;
                    }
                    // 找到模型id对应的模型
                    LambdaQueryWrapper<MdlModel> lambda2 = new QueryWrapper().lambda();
                    lambda2.eq(MdlModel::getId,modelId);
                    //config字段太大 不返回
                    lambda2.select(MdlModel::getId,MdlModel::getName,MdlModel::getType,MdlModel::getUseCount,MdlModel::getDescription,MdlModel::getSampleLayerUrl,MdlModel::getCalculate,MdlModel::getIntroduce,MdlModel::getLevelStandard,MdlModel::getCalculateProcess,MdlModel::getResultLayer,MdlModel::getCreator,MdlModel::getCreateTime,MdlModel::getModifier,MdlModel::getModifyTime);
                    item.setMdlModel(mdlModelService.getOne(lambda2));
                    if(isQueryResult){
                        //查询模型结果
                        LambdaQueryWrapper<MdlModelResult> lambda1 = new QueryWrapper().lambda();
                        lambda1.eq(MdlModelResult::getYear,year);
                        lambda1.like(MdlModelResult::getModelIds,modelId);
                        List<MdlModelResult> list1 = mdlModelResultService.list(lambda1);
                        if(list1!=null&&list1.size()>0){
                            MdlModelResult mdlModelResult = list1.get(0);
                            String result = mdlModelResult.getResult();
                            if(StringUtils.isNotBlank(result) && StringUtils.isNotBlank(areaCode)){
                                JSONObject jsonObject = JSONObject.fromObject(result);
                                JSONObject rootGroupItem = null;
                                // 有多种数据格式
                                if(jsonObject.containsKey(ModelConst.MODEL_LEVEL_ROOTGROUPITEM)){
                                   rootGroupItem = jsonObject.getJSONObject(ModelConst.MODEL_LEVEL_ROOTGROUPITEM);
                                }else{
                                    rootGroupItem = jsonObject;
                                }
                                String cityField = ModelConst.MODEL_FEATURE_DIVISION_GROUPITEMCODE;
                                if(!rootGroupItem.containsKey(ModelConst.MODEL_FEATURE_DIVISION_GROUPITEMCODE)){
                                    cityField= "AreaCode";
                                }

                                if(!areaCode.equals(rootGroupItem.getString(cityField))){
                                    rootGroupItem.put(ModelConst.MODEL_STATISTICAL_STATISTICINFORMATION,new JSONObject());
                                    String key = null;
                                    if(rootGroupItem.containsKey("LstCityModel")){
                                        key= "LstCityModel";
                                    }
                                    if(rootGroupItem.containsKey(ModelConst.MODEL_LEVEL_SUBLEVEL1GROUPITEM)){
                                        key= ModelConst.MODEL_LEVEL_SUBLEVEL1GROUPITEM;
                                    }
                                    JSONArray subLevel1GroupItems = rootGroupItem.getJSONArray(key);
                                    //递归模型结果数据,将不可看的城市数据设置为空
                                    if(subLevel1GroupItems!=null && subLevel1GroupItems.size()>0){
                                        recursionData(subLevel1GroupItems,areaCode,cityField);
                                    }
                                }
                                mdlModelResult.setResult(jsonObject.toString());
                            }

                            item.setMdlModelResult(mdlModelResult);
                        }
                    }
                }
            }
        }
        // 汤厚韬 2020-12-25
        // 框架升级后，没有convertService，该字段不知匹配哪个字典，对照匹配字典前后无差别，故先注释。
        // 需优化
        // keys.put("typeCode","ZXPG");
        // convertService.toEntityList(mdlModelDirs,keys);
        mdlModelDirs.stream().forEach(item ->{
            if(item.getTypeCode().length() == 32 ){
                item.setTypeCode(null);
            }
        });
        return new AjaxResult(RecursionUtils.buildModelDirTree2(mdlModelDirs,one.getId()));
    }

    /**
    * @描述:递归模型结果城市，将不可见城市的StatisticInformation设置为空
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/7/14 17:28
    **/
    public static  void recursionData(JSONArray jsonObject,String areaCode,String cityField){
        for (int i = 0; i < jsonObject.size() ; i++) {
            JSONObject subObj = jsonObject.getJSONObject(i);
            if(!areaCode.equals(subObj.getString(cityField))){
                subObj.put(ModelConst.MODEL_STATISTICAL_STATISTICINFORMATION,new JSONObject());
                String key = null;
                if(subObj.containsKey("LstCityModel")){
                    key= "LstCityModel";
                }
                if(subObj.containsKey(ModelConst.MODEL_STATISTICAL_LSTCOUNTYMODELEX)){
                    key= ModelConst.MODEL_STATISTICAL_LSTCOUNTYMODELEX;
                }
                if(subObj.containsKey(ModelConst.MODEL_LEVEL_SUBLEVEL1GROUPITEM)){
                    key= ModelConst.MODEL_LEVEL_SUBLEVEL1GROUPITEM;
                }
                if(key != null){
                    JSONArray subLevel1GroupItems = subObj.getJSONArray(key);
                    //递归模型结果数据 将不可看的城市数据设置为空
                    if(subLevel1GroupItems!=null && subLevel1GroupItems.size()>0){
                        recursionData(subLevel1GroupItems,areaCode,cityField);
                    }
                }

            }
        }

    }
}
